
import argparse
import sys
import zipfile
import os
import re
import shutil
import logging

import xlwings as xw

from metric import MetricParser
from web_tool import WebTool


class CompareParser:
    def __init__(self, input_file_list):
        self.input_file_list = input_file_list
    
    def parse(self):
        for input_path in self.input_file_list:
            self.parse_one_file(input_path)

    def parse_one_file(self, input_path):
        wb = xw.Book(input_path)
        sheet = wb.sheets[0]
        max_row = sheet.used_range.last_cell.row
        max_col = sheet.used_range.last_cell.column
        print(f'max row:{max_row}  max col:{max_col}')
        sheet.range((9, max_col)).copy(sheet.range((9, max_col+1), (9, max_col+3)))
        sheet.range((9, max_col+1)).value = "帧率方差"
        sheet.range((9, max_col+2)).value = "1%low帧"
        sheet.range((9, max_col+3)).value = "CPU Usage"

        download_path = os.path.join(os.path.dirname(input_path), 'temp_file')
        print(f'清空文件夹:{download_path}')
        if os.path.exists(download_path):
            shutil.rmtree(download_path)
        web_tool = WebTool(download_path)
        for row in range(1, max_row + 1):
            for col in range(1, max_col + 1):
                cell_hyperlink = sheet.range((row, col))
                if cell_hyperlink.value == '任务详情':
                    files = os.listdir(download_path)
                    files = [f for f in files if '.' in f and f.split('.')[-1] == 'csv']
                    for file in files:
                        os.remove(os.path.join(download_path, file))
                    cell_machine_type = sheet.range((row, 3))
                    row, variance_population, one_percent_low_frame, cpu_usage = CompareParser.process_func(web_tool, row, cell_hyperlink.hyperlink, cell_machine_type.value)
                    sheet.range((row, max_col+1)).value = variance_population
                    sheet.range((row, max_col+2)).value = one_percent_low_frame
                    sheet.range((row, max_col+3)).value = cpu_usage

        web_tool.driver.quit()
        wb.save()
        print(f'保存文件:{input_path}')

    @staticmethod
    def process_func(web_tool, row, cell_hyperlink_url, cell_machine_type):
        url = cell_hyperlink_url
        device_type =cell_machine_type.split('-')[0]

        match = re.search(r'=(.*)', url)
        num = match.group(1).strip()
        web_tool.download_file(url)

        zip_file_path = os.path.join(web_tool.default_download_path, f'smartPref_{num}.zip')
        print(f'解压文件:{zip_file_path}')
        zf = zipfile.ZipFile(zip_file_path)
        zf.extractall(web_tool.default_download_path)
        
        parser = MetricParser(device_type, os.path.join(web_tool.default_download_path, 'IndexInfo.csv'))
        variance_population, one_percent_low_frame, cpu_usage = parser.parse_one(
            os.path.join(web_tool.default_download_path, 'IndexInfo.csv'))
        
        return row, variance_population, one_percent_low_frame, cpu_usage


def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-i', '--input_source',
                        action='append',
                        type=str,
                        help="""input compare file""")
    args = parser.parse_args()
    if not args.input_source:
        print("invalid parameter input_source")
        return

    compare_parser = CompareParser(args.input_source)
    try:
        compare_parser.parse()
    except Exception as e:
        logging.exception(e)
    input('Press ENTER to exit...')

def main_binary(input_source):
    compare_parser = CompareParser(input_source)
    try:
        compare_parser.parse()
    except Exception as e:
        logging.exception(e)
    input('Press ENTER to exit...')

if __name__ == '__main__':
    if getattr(sys, 'frozen', False):
        main_binary(sys.argv[1:])
    else:
        main()